/*
 * tcp_listen.c
 *
 *  Created on: 2012-2-27
 *      Author: skyrain
 */

#include "skynet.h"
#include <time.h>

int tcp_port_listen(const int port, const char *ipstr)
{

	int listenfd, connfd, createcount = 0;
	struct sockaddr_in servaddr;

	create_again: if ((listenfd = socket(AF_UNSPEC, SOCK_DGRAM, 0)) == -1)
	{
		createcount++;
		if (createcount < 3)
			goto create_again;
		else
			err_quit("socket create is error");
	}
	bzero(&servaddr, sizeof(struct sockaddr_in));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(port);
	servaddr.sin_addr = htonl(INADDR_ANY);

	if (bind(listenfd, (struct sockaddr *) &servaddr, sizeof(struct servaddr)) == -1)
		err_quit("socketfd bind error");

	if (listen(listenfd, LISTENQ) == -1)
		err_quit("socket listen error");

	return listenfd;

}

void Pthread_create(pthread_t *tid, const pthread_attr_t *attr, void * (*func)(void *), void *arg)
{
	int n;

	if ((n = pthread_create(tid, attr, func, arg)) == 0)
		return;
	errno = n;
	err_sys("pthread_create error");
}

int Sendmsg_tcp(const int sockfd, struct iovec* msg_iov, int msg_iovlen, int flags)
{

	struct msghdr *msg = NULL;
	int sendcount = -1;
	int temperrno;
	if ((msg = calloc(1, sizeof(struct msghdr))) == NULL)
	{
		err_msg("sendmsg is error");
		return -sendcount;
	}
	msg->msg_iov = msg_iov;
	msg->msg_iovlen = msg_iovlen;

	if ((sendcount = sendmsg(sockfd, msg, flags)) == -1)
	{
		//试着加入判断errno功能 ，决定是否直接关闭套接字
		/*temperrno = errno;
		 * if(errno == ...)
		 * 		close(sockfd);
		 * 		这留着提醒 自己。关闭套接字留给上层函数，这里只返回错误
		 */
		err_msg("sendmsg is error");
	}
	free(msg);
	return sendcount;
}
u_int32_t time2int()
{
	u_int8_t count = 0;
	int re_value = 0;
	char s[10];
	struct tm* t;
	time_t now;

	bzero(s, 0);

	while ((now = time(NULL)) == -1 && (count++) < 3){}

	if(now == -1)
	{
		return re_value;
	}

	strftime(s, 10, "%m-%d-%H %M:%S", localtime(&now));
	re_value = atoi(s);
	return re_value;
}
